package com.imay.live.activity;

import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.v4.view.ViewPager;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.imay.cocos.IMayCocos;
import com.imay.live.R;
import com.imay.live.fragment.PopupMenuFragment;
import com.imay.live.fragment.room.LinkMicInviteDialog;
import com.imay.live.fragment.room.RoomGuideFragment;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.helper.ThreadManager;
import com.imay.live.manager.AccountManager;
import com.imay.live.model.MenuItemModel;
import com.imay.live.proto.MessageId;
import com.imay.live.proto.room.RoomCommonResp;
import com.imay.live.proto.room.RoomLinkInviteNotify;
import com.imay.live.proto.room.RoomSetLiveStatusReq;
import com.imay.live.proto.user.UserInfoCard;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.viewpager.CViewPager;

import java.util.ArrayList;


/**
 * Created by jeaman on 2017/3/28.
 */

public abstract class RoomLiveBaseActivity extends RoomBaseActivity implements View.OnClickListener {
    protected View mCloseView;
    protected CViewPager mViewPager;
    protected ImageView mCoverIv;

//    protected ChangeRoomAdapter mAdapter;
//    private List<RoomInfoModel> mRoomList;


    private ArrayList<MenuItemModel> mAdminMenuList = new ArrayList<>();
    private String mCoverUrl;

    protected boolean mEndLive = false;   //直播已结束
    private int mLastPosition = 0;

    private boolean mScrolling = false;

    private GestureDetector mGestureDetector;
    private float mFlingX;    //上下滑动阈值
    private float mFlingY;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live1;
    }

    @CallSuper
    @Override
    protected void initView(Bundle savedInstanceState) {
        mCloseView = $(R.id.live_iv_close);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mCloseView.getLayoutParams();
        layoutParams.setMargins(layoutParams.leftMargin, getStatusBarHeight(), layoutParams.rightMargin, layoutParams.bottomMargin);

        mLiveVideoView = $(R.id.live_lvv_video);
        mCoverIv = $(R.id.live_iv_cover);
        mViewPager = $(R.id.live_vp_viewpager);
        ViewGroup rootView = $(R.id.live_rl_root);

        initRoomView();
        rootView.addView(mRoomView, 1);
        initPlayer(mLiveVideoView.getVideoView());
        initListener();
        initMenu();

        registerNotify();

        //新手指引
        if (!PreferenceHelper.getInstance().getRoomGuide()) {
            DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), RoomGuideFragment. newInstance());
            PreferenceHelper.getInstance().saveRoomGuide();
        }
    }

    protected void changeRoom(int position) {
        if (mRoomId != 0) {
            cocosExitRoomByType();   //cocos先退出房间
        }

        mHasFollowed = false;
        mHasShared = false;
        mLivePlayer.stopPlay();
        mRoomView.reset();

        setCoverViewVisibility(mLastPosition, true); //显示viewpager封面
        mLastPosition = position;
        onChangeRoom(position);

        //恢复cocos相关设置
        mRoomView.resetCocosSetting();
        onCocosSetHorizontalScrollEnabled(true);
        onCocosSetVerticalScrollEnabled(true);
    }

    //离开房间
    protected abstract void requestLeaveRoom();

    protected abstract void onChangeRoom(int position);

    protected void onJoinRoom(UserInfoCard userInfo) {
        mRoomId = userInfo.roomId;
        setAnchorInfo(userInfo);
        setCoverUrl(userInfo.imgHead);

        mRoomView.setAnchorInfo(userInfo);
        if (userInfo.uid == AccountManager.getInstance().getUid()) {
            mRoomView.setFollowUser(true);  //自己隐藏关注按钮
        }
        setCoverViewVisibility(mLastPosition, false); //隐藏viewpager封面
    }

    @CallSuper
    protected void onLiveEnd() {
        if (mLivePlayer != null) {
            mLivePlayer.stopPlay();
        }
    }

    protected abstract void setCoverViewVisibility(int position, boolean visible);

    @Override
    protected boolean isMainPublisher() {
        return false;   //观众端
    }

    private void initMenu() {
        mAdminMenuList.add(new MenuItemModel(MENU_ACTION_INFORM, R.string.live_menu_inform));
        mAdminMenuList.add(new MenuItemModel(MENU_ACTION_SILENCE, R.string.live_menu_silence));
        mAdminMenuList.add(new MenuItemModel(MENU_ACTION_KICK, R.string.live_menu_kick));
    }

    protected void initListener() {
        mCloseView.setOnClickListener(this);
        mViewPager.setDispatchTouchViewGroup(mRoomView);//触摸事件分发
        mRoomView.setOnActionListener(this);
        mViewPager.setInterceptView(mRoomView.getChatRecyclerView());   //用户列表滑动到两端不触发ViewPager滑动
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                mLiveVideoView.requestLayout();//必须requestLayout，否则滑动时，GLSurfaceView会导致黑屏
            }

            @Override
            public void onPageSelected(final int position) {
                changeRoom(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    mScrolling = false;
                } else {
                    mScrolling = true;
                }
            }
        });
        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mGestureDetector.onTouchEvent(event);
            }
        });

        mFlingX = getResources().getDimension(R.dimen.room_fling_x);
        mFlingY = getResources().getDimension(R.dimen.room_fling_y);
        mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {


            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                if (mRoomView == null) {
                    return false;
                }
                if (mRoomView.isHideAllView() || mRoomView.isUserListScrolling()) { //未进入房间前或者用户列表正在滑动
                    return false;
                }
                //左右滑动隐藏view
                if (!mScrolling && Math.abs(e2.getY() - e1.getY()) < mFlingY) {
                    boolean result = false;
                    if (e2.getX() - e1.getX() > mFlingX) {
                        result = mRoomView.toggleSimpleMode(true);
                        if (result) {
                            IMayCocos.setRoomSimpleMode(true);
                        }
                    } else if (e1.getX() - e2.getX() > mFlingX) {
                        result = mRoomView.toggleSimpleMode(false);
                        if (result) {
                            IMayCocos.setRoomSimpleMode(false);
                        }
                    }
                    return result;
                }
                return false;
            }
        });
    }

    //处理直播状态
    protected void processLiveStatus(int liveStatus) {
        switch (liveStatus) {
            case RoomSetLiveStatusReq.LIVE_ING: //直播中
                if (mRoomView != null) {
                    mRoomView.hideLiveStatusTips();
                }
                mEndLive = false;
                startPlay();
                break;
            case RoomSetLiveStatusReq.LIVE_END: //直播已结束
                mEndLive = true;
                if (mRoomView != null) {
                    mRoomView.hideLiveStatusTips();
                }
                onLiveEnd();
                break;
            case RoomSetLiveStatusReq.LIVE_BUSY:    //主播网络不稳定
                ToastUtil.show(this, R.string.live_status_busy);
                break;
            case RoomSetLiveStatusReq.LIVE_PAUSE:   //主播进入后台
                if (mRoomView != null) {
                    mRoomView.showLiveStatusTips(getString(R.string.live_status_background));
                }
                break;
            case RoomSetLiveStatusReq.LIVE_RESUME:  //主播回到前台
                if (mRoomView != null) {
                    mRoomView.hideLiveStatusTips();
                }
                break;
            case RoomSetLiveStatusReq.LIVE_RECONNECT:
                break;
        }
    }

    @Override
    protected void processSocketNotify(int msgId, String content) {
        switch (msgId) {
            case MessageId.roomLinkInviteNotify:    //主播连麦邀请
                final RoomLinkInviteNotify roomLinkInviteNotify = JSON.parseObject(content, RoomLinkInviteNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomLinkInviteNotify.roomId) {
                            DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), LinkMicInviteDialog.newInstance());
                        }
                    }
                });
                break;
            case MessageId.roomLiveStatusNotify:    //直播状态通知
                final RoomSetLiveStatusReq roomSetLiveStatusReq = JSON.parseObject(content, RoomSetLiveStatusReq.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomSetLiveStatusReq.roomId) {
                            processLiveStatus(roomSetLiveStatusReq.status);
                        }
                    }
                });
                break;
            case MessageId.roomContinueLiveNotify:  //继续直播
                final RoomCommonResp roomContinuLiveNotify = JSON.parseObject(content, RoomCommonResp.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (roomContinuLiveNotify.roomId == getRoomId()) {
                            processLiveStatus(RoomSetLiveStatusReq.LIVE_ING);
                        }
                    }
                });
                break;
            case MessageId.roomEndLiveNotify:   //结束直播
                final RoomCommonResp roomEndLiveNotify = JSON.parseObject(content, RoomCommonResp.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (roomEndLiveNotify.roomId == getRoomId()) {
                            processLiveStatus(RoomSetLiveStatusReq.LIVE_END);
                        }
                    }
                });
                break;
            case MessageId.roomStartLiveNotify: //开始直播
                final RoomCommonResp roomStartLiveNotify = JSON.parseObject(content, RoomCommonResp.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (roomStartLiveNotify.roomId == getRoomId()) {
                            processLiveStatus(RoomSetLiveStatusReq.LIVE_ING);
                        }
                    }
                });
                break;
        }
    }

    @Override
    protected String getCoverUrl() {
        return mCoverUrl;
    }

    @Override
    public void showAdminMenu(UserInfoCard userInfoCard) {
        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), PopupMenuFragment.newInstance(mAdminMenuList), FRAGMENT_TAG_MANAGER_MENU);
    }

    //封流、封房
    @Override
    protected void onLiveBlock(long uid) {
        if (mAnchorInfo != null && uid == mAnchorInfo.uid) {
            ToastUtil.show(this, R.string.tips_forbidden_room);
            processLiveStatus(RoomSetLiveStatusReq.LIVE_END);
        }
    }

    @Override
    public void onCocosSetHorizontalScrollEnabled(boolean enabled) {
        //cocos设置是否允许水平滚动
        mViewPager.setCanTouch(enabled);
    }

    @Override
    public void onCocosSetVerticalScrollEnabled(boolean enabled) {
        //cocos设置是否允许垂直滚动
        mViewPager.setCanScroll(enabled);
    }

    @Override
    public void onDestroy() {
        requestLeaveRoom();
        super.onDestroy();
    }

    @CallSuper
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.live_iv_close:
                onBackPressed();
        }
    }

    @CallSuper
    @Override
    public void onPlayBegin() {
        mLiveVideoView.bringToFront();
    }

    public void setCoverUrl(String coverUrl) {
        this.mCoverUrl = coverUrl;
    }
}

